package com.Dao;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.database.Mysql;
import com.news.model.News;

import java.util.ArrayList;
import java.util.List;
public class NewsDao {
    private SQLiteDatabase db;
    private Mysql dbHelper;

    public NewsDao(Context context) {
        dbHelper = new Mysql(context);
        db = dbHelper.getWritableDatabase();
    }

    // 关闭数据库连接（通常在DAO的销毁方法中调用）
    public void close() {
        db.close();
    }

    // 插入新闻
    public long insertNews(News news) {
        ContentValues values = new ContentValues();
        values.put("title", news.getTitle());
        values.put("content", news.getContent());
        values.put("category", news.getCategory());
        values.put("author", news.getAuthor());
        values.put("publishedAt", news.getPublishedAt());
        values.put("imageUrl", news.getImageUrl());

        return db.insert("news", null, values);
    }

    // 查询所有新闻
    @SuppressLint("Range")
    public List<News> getAllNews() {
        List<News> newsList = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = dbHelper.getReadableDatabase();
            cursor = db.query("news", null, null, null, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    News news = new News();

                    int newsIdIndex = cursor.getColumnIndex("newsid");
                    if (newsIdIndex != -1) {
                        news.setNewsId(cursor.getInt(newsIdIndex));
                    } else {
                        Log.e("Database", "Column newsid not found");
                        // 根据实际情况，可以抛出异常或返回空列表
                        // throw new IllegalStateException("news_id column not found");
                        // 或者
                        // continue; // 跳过当前循环，继续处理下一条新闻
                    }

                    int titleIndex = cursor.getColumnIndex("title");
                    if (titleIndex != -1) {
                        news.setTitle(cursor.getString(titleIndex));
                    } else {
                        Log.e("Database", "Column title not found");
                    }

                    int contentIndex = cursor.getColumnIndex("content");
                    if (contentIndex != -1) {
                        news.setContent(cursor.getString(contentIndex));
                    } else {
                        Log.e("Database", "Column content not found");
                    }

                    int categoryIndex = cursor.getColumnIndex("category");
                    if (categoryIndex != -1) {
                        news.setCategory(cursor.getString(categoryIndex));
                    }

                    int authorIndex = cursor.getColumnIndex("author");
                    if (authorIndex != -1) {
                        news.setAuthor(cursor.getString(authorIndex));
                    }

                    int publishedAtIndex = cursor.getColumnIndex("publishedAt");
                    if (publishedAtIndex != -1) {
                        long timestamp = cursor.getLong(publishedAtIndex); // 假设是长整型时间戳
                        news.setPublishedAt(timestamp); // 确保News类中的setPublishedAt方法接受长整型参数
                    }

                    int imageUrlIndex = cursor.getColumnIndex("imageUrl");
                    if (imageUrlIndex != -1) {
                        news.setImageUrl(cursor.getString(imageUrlIndex));
                    }
                    newsList.add(news);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Log.e("Database", "Error fetching news", e);
            // 在这里可以添加更详细的错误处理逻辑
        } finally {
            // 关闭Cursor和Database，确保资源得到释放
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
        return newsList;
    }

    //根据newsid查询新闻
    public News getNewsByNewsid(int id) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        News news = null;
        try {
            db = dbHelper.getReadableDatabase();
            cursor = db.query("news", null, "newsid = ?", new String[]{String.valueOf(id)}, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                news = new News();
                int newsIdIndex = cursor.getColumnIndex("newsid");
                int titleIndex = cursor.getColumnIndex("title");
                int contentIndex = cursor.getColumnIndex("content");
                int categoryIndex = cursor.getColumnIndex("category");
                int authorIndex = cursor.getColumnIndex("author");
                int publishedAtIndex = cursor.getColumnIndex("publishedAt");
                int imageUrlIndex = cursor.getColumnIndex("imageUrl");

                if (newsIdIndex != -1) {
                    news.setNewsId(cursor.getInt(newsIdIndex));
                }
                if (titleIndex != -1) {
                    news.setTitle(cursor.getString(titleIndex));
                }
                if (contentIndex != -1) {
                    news.setContent(cursor.getString(contentIndex));
                }
                if (categoryIndex != -1) {
                    news.setCategory(cursor.getString(categoryIndex));
                }
                if (authorIndex != -1) {
                    news.setAuthor(cursor.getString(authorIndex));
                }
                if (publishedAtIndex != -1) {
                    long timestamp = cursor.getLong(publishedAtIndex);
                    news.setPublishedAt(timestamp);
                }
                if (imageUrlIndex != -1) {
                    news.setImageUrl(cursor.getString(imageUrlIndex));
                }
            }
        } catch (Exception e) {
            Log.e("Database", "Error fetching news", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return news; // 返回单个News对象
    }
    //根据分类获取新闻
    public List<News> getNewsByCategory(String category) {
        List<News> newsList = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = dbHelper.getReadableDatabase();
            // 使用WHERE子句来过滤特定分类的新闻
            cursor = db.query("news", null, "category=?", new String[]{category}, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    News news = new News();

                    int newsIdIndex = cursor.getColumnIndex("newsid");
                    if (newsIdIndex != -1) {
                        news.setNewsId(cursor.getInt(newsIdIndex));
                    } else {
                        Log.e("Database", "Column newsid not found");
                    }

                    int titleIndex = cursor.getColumnIndex("title");
                    if (titleIndex != -1) {
                        news.setTitle(cursor.getString(titleIndex));
                    } else {
                        Log.e("Database", "Column title not found");
                    }

                    int contentIndex = cursor.getColumnIndex("content");
                    if (contentIndex != -1) {
                        news.setContent(cursor.getString(contentIndex));
                    } else {
                        Log.e("Database", "Column content not found");
                    }

                    int categoryIndex = cursor.getColumnIndex("category");
                    if (categoryIndex != -1) {
                        news.setCategory(cursor.getString(categoryIndex));
                    }

                    int authorIndex = cursor.getColumnIndex("author");
                    if (authorIndex != -1) {
                        news.setAuthor(cursor.getString(authorIndex));
                    }

                    int publishedAtIndex = cursor.getColumnIndex("publishedAt");
                    if (publishedAtIndex != -1) {
                        long timestamp = cursor.getLong(publishedAtIndex);
                        news.setPublishedAt(timestamp);
                    }

                    int imageUrlIndex = cursor.getColumnIndex("imageUrl");
                    if (imageUrlIndex != -1) {
                        news.setImageUrl(cursor.getString(imageUrlIndex));
                    }
                    newsList.add(news);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Log.e("Database", "Error fetching news by category", e);
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            if (db != null && db.isOpen()) {
                db.close();
            }
        }

        return newsList;
    }
    // 更新新闻（根据newsid）
    public int updateNews(News news) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", news.getTitle());
        values.put("content", news.getContent());
        // ... 其他字段 ...

        int rowsUpdated = db.update("news", values, "newsid = ?", new String[]{String.valueOf(news.getNewsId())});
        db.close(); // 更新后关闭数据库连接
        return rowsUpdated;
    }

    // 删除新闻（根据news_id）
    public void deleteNews(int newsId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("news", "news_id = ?", new String[]{String.valueOf(newsId)});
        db.close(); // 删除后关闭数据库连接
    }

}